package com.srxz.mobilepharmacy.service;

import com.alibaba.fastjson.JSON;
import com.srxz.mobilepharmacy.entity.ClinicRec;
import com.srxz.mobilepharmacy.entity.ClinicRecPK;
import com.srxz.mobilepharmacy.entity.ClinicRecView;
import com.srxz.mobilepharmacy.entity.UserInfoPK;
import com.srxz.mobilepharmacy.repository.ClinicRecRepository;
import com.srxz.mobilepharmacy.repository.ClinicRecViewRepository;
import com.srxz.mobilepharmacy.util.LogTool;
import com.srxz.mobilepharmacy.util.SessionTool;
import com.srxz.mobilepharmacy.util.back.BackMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpSession;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class ClinicRecService {
    @Autowired
    private ClinicRecViewRepository clinicRecViewRepository;
    @Autowired
    private ClinicRecRepository clinicRecRepository;
    @PersistenceContext //注入的是实体管理器,执行持久化操作
     EntityManager entityManager;

    public BackMessage findAllRec(BigInteger aid, Boolean now, String search, HttpSession session) throws ParseException {
        Date ntime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String day = sdf.format(ntime);
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date nday = sdf.parse(day+" 00:00:00");
        System.out.println(sdf.format(nday));
        Object[] views = null;
        //获取登陆药房编号
        Integer mrn = SessionTool.getHouse(session);
        if(mrn == null)
            return BackMessage.error("请重新登陆选择药房");
        if(StringUtils.isEmpty(search))
            search = "";
        if(now)
            views = clinicRecViewRepository.findallrecAfter(aid, nday, "%"+search+"%", mrn);
        else
            views = clinicRecViewRepository.findallrecBefore(aid, nday, "%"+search+"%", mrn);

        List<ClinicRecView> clinicRecViews = new ArrayList<>();
        for(int i=0; i<views.length; i++){
            Object[] col = (Object[]) views[i];
            ClinicRecView clinicRecView = new ClinicRecView();

            clinicRecView.setPayer(col[0].toString());
            clinicRecView.setAid(new BigInteger(col[1].toString()));
            clinicRecView.setPatid(new BigInteger(col[2].toString()));
            clinicRecView.setSn(new BigInteger(col[3].toString()));
            String sdate = col[4].toString().substring(0, col[4].toString().lastIndexOf("."));
            clinicRecView.setDt(sdf.parse(sdate));
            clinicRecView.setSex(col[5].toString());
            clinicRecView.setYears(new Integer(col[6].toString()));

            clinicRecViews.add(clinicRecView);
        }

        return BackMessage.success().putData("clinicRecViews", clinicRecViews);
    }

    public BackMessage findRec(BigInteger aid, BigInteger patid, BigInteger sn) throws ParseException{
        if(aid == null || patid == null){
            return BackMessage.error("信息不完整");
        }
        String SQL = "select * from vw_门诊费用 clinicrecv0_ where clinicrecv0_.aid="+aid+" " +
                "and mid > 999999 and clinicrecv0_.sn=" +sn+
                " and clinicrecv0_.patid="+patid+" and (clinicrecv0_.smed is null or clinicrecv0_.smed='')";
        List<Object[]> res = entityManager.createNativeQuery(SQL).getResultList();
        System.out.println(JSON.toJSONString(res));
        List<ClinicRecView> clinicRecViews = new ArrayList<>();
        for(Object[] obj:res){
            ClinicRecView clinicRecView = new ClinicRecView(obj);
            clinicRecViews.add(clinicRecView);
        }
        return BackMessage.success().putData("clinicRecViews", clinicRecViews);
    }

    public BackMessage dispensing(List<ClinicRecPK> clinicRecPKs, HttpSession session){
        UserInfoPK uid = SessionTool.getUser(session);
        Integer msn = SessionTool.getHouse(session);
        long bs = System.currentTimeMillis();
        //日志记录
        LogTool.pdLog(1, bs, uid, clinicRecPKs, msn.toString());
        //当前操作员
        UserInfoPK id = SessionTool.getUser(session);

        for(ClinicRecPK clinicRecPK:clinicRecPKs){
            //TODO 仅设置发药人、更新发药时间
            ClinicRec clinicRec = clinicRecRepository.findById(clinicRecPK).orElse(null);
            clinicRec.setSmed(id.getName());
            clinicRec.setSdate(new Date());
            clinicRec = clinicRecRepository.save(clinicRec);
        }
        LogTool.resLog(1, bs, "发药成功");
        return BackMessage.success();
    }
}
